import 'package:flutter/material.dart';

class GradientIndicator extends Decoration {
  final TabController? tabController;
  final double indicatorBottom; // 调整指示器下边距
  final double indicatorWidth; // 指示器宽度
  final double indicatorHeight; // 指示器高度
  final List<Color> gradientColors; // 渐变色列表

  const GradientIndicator({
    this.tabController,
    this.indicatorBottom = 0.0,
    this.indicatorWidth = 4,
    this.indicatorHeight = 4,
    required this.gradientColors,
  });

  @override
  BoxPainter createBoxPainter([VoidCallback? onChanged]) {
    return _GradientPainter(
      this,
      onChanged,
      tabController?.animation,
      indicatorWidth,
      indicatorHeight,
    );
  }

  Rect _indicatorRectFor(Rect indicator, TextDirection textDirection) {
    double w = indicatorWidth;
    double centerWidth = (indicator.left + indicator.right) / 2;
    return Rect.fromLTWH(
      tabController?.animation == null ? centerWidth - w / 2 : centerWidth - w / 2,
      indicator.bottom - indicatorHeight - indicatorBottom,
      w,
      indicatorHeight,
    );
  }

  @override
  Path getClipPath(Rect rect, TextDirection textDirection) {
    return Path()..addRect(_indicatorRectFor(rect, textDirection));
  }
}

class _GradientPainter extends BoxPainter {
  Animation<double>? animation;
  double indicatorWidth;
  double indicatorHeight;

  _GradientPainter(this.decoration, VoidCallback? onChanged, this.animation,
      this.indicatorWidth, this.indicatorHeight)
      : super(onChanged);

  final GradientIndicator decoration;

  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
    assert(configuration.size != null);
    final Rect rect = offset & configuration.size!;
    final TextDirection textDirection = configuration.textDirection!;
    final Rect indicator = decoration._indicatorRectFor(rect, textDirection)
      ..deflate(decoration.indicatorWidth / 2.0);

    // 创建渐变画笔
    final Paint paint = Paint()
      ..shader = LinearGradient(
        colors: decoration.gradientColors,
      ).createShader(indicator);

    // 绘制指示器
    canvas.drawRRect(
      RRect.fromRectAndRadius(indicator, Radius.circular(2)),
      paint,
    );
  }
}
